use actix_web::{post, web::ServiceConfig, Scope};
use serde::Deserialize;

use crate::{error::AppErr, store::dev_type::{self, DevType}, web::{req::Cbor, res::{new_body, CborResp, VoidResp}, session::Session}};

#[derive(Debug, Deserialize)]
struct CreateReq {
    name: String
}

#[post("/create")]
pub async fn create(_s: Session, req: Cbor<CreateReq>) -> CborResp<DevType> {
    let ret = dev_type::create(&req.name).await?;
    new_body(ret)
}

#[derive(Debug, Deserialize)]
struct IdReq {
    id: i64,
}

#[post("/delete")]
pub async fn delete(_s: Session, req: Cbor<IdReq>) -> Result<VoidResp, AppErr> {
    dev_type::delete(req.id).await?;
    Ok(VoidResp)
}

#[post("/query")]
pub async fn query(_s: Session) -> CborResp<Box<[DevType]>> {
    new_body( dev_type::query().await? )
}

pub fn register(cfg: &mut ServiceConfig) {
    let socpe = Scope::new("/dev_type")
        .service(create)
        .service(delete)
        .service(query)
    ;

    cfg.service(socpe);
}
